package com.tanhua.admin.interceptor;

import com.alibaba.fastjson.JSON;

import com.tanhua.model.admin.Admin;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * 自定义拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 前置处理
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取头信息
        String token = request.getHeader("Authorization");
        log.error(token);
        log.info("请求了路径："+ request.getRequestURI());
        //2、如果没有token，权限不足 （返回false）
        if(StringUtils.isNotEmpty(token)) {
            token = token.replace("Bearer ", "");
            //3、从redis中取出,并解析成用户对象
            String tokenKey = "TOKEN_" + token;
            String adminJsonString = stringRedisTemplate.opsForValue().get(tokenKey);
            if(StringUtils.isNotEmpty(adminJsonString)){
                try {
                    Admin admin = JSON.parseObject(adminJsonString, Admin.class);
                    //4、将对象存入线程
                    AdminHolder.set(admin);
                    // 重新设置token有效期 30分钟
                    stringRedisTemplate.expire(tokenKey, Duration.ofMinutes(30));
                    return true;
                } catch (Exception e) {
                    log.error("解析登录用户数据失败!",e);
                }
            }
        }
        return false;
    }
}
